document.addEventListener('DOMContentLoaded', () => {
  getCurrentTime();
  getWeather();
  // 每隔一秒更新时间
  const getTime = setInterval(getCurrentTime, 1000);

  /*------------------------数据显示区 start------------------------*/
  // 加载完成先调用 获取一次数据
  get_info();
  // 定时器 每隔 1min
  /*------------------------数据显示区 end---------------------------*/

  /*-------------------------控制区 start---------------------------*/
  // 设备控制
  const flags = [0, 0, 0]
  const btns = document.querySelectorAll('.control button')
  const on_off = document.querySelectorAll('.left span')
  const img = document.querySelectorAll('.middle')
  // const ul = document.querySelector('ul')
  // const speed = document.querySelectorAll('ul a')
  for (let i = 0; i < flags.length; i++) {
    flags[i] = btns[i].innerHTML === 'ON' ? 1 : 0
  }

  // if (flags[1] == 0) {
  //   ul.classList.remove('disable')
  //   speed[0].classList.add('active')
  // }

  const btnClick = (index) => {
    btns[index].innerHTML = flags[index] == 1 ? 'OFF' : 'ON'
    on_off[index].innerHTML = flags[index] == 1 ? 'ON' : 'OFF'

    flags[index] = !flags[index]
  }
  btns[0].addEventListener('click', () => {
    // 改变设备状态
    change_statu(106, flags[0])
    btnClick(0)
    img[0].classList = flags[0] == 1 ? 'middle iconfont icon-guandeng-light-off' : 'middle iconfont icon-kaideng-light-on'
  })
  btns[1].addEventListener('click', () => {
    // 改变设备状态
    change_statu(105, flags[1])
    btnClick(1)
    img[1].classList = flags[1] == 1 ? 'middle iconfont icon-fengshanguan' : 'middle iconfont icon-fengshankai'
    // 关闭 禁用超链接
    // if (flags[1]) {
    //   ul.classList.add('disable')
    //   for (let i = 0; i < speed.length; i++)
    //     speed[i].classList.remove('active')
    // }
    // // 打开 默认小风
    // else {
    //   ul.classList.remove('disable')
    //   speed[0].classList.add('active')
    // }
  })
  btns[2].addEventListener('click', () => {
    // 改变设备状态
    change_statu(104, flags[2])
    btnClick(2)
    img[2].classList = flags[2] == 1 ? 'middle iconfont icon-yidongduan-' : 'middle iconfont icon-kongtiao'
  })

  // 风速控制
  // ul.addEventListener('click', (e) => {
  //   for (let i = 0; i < speed.length; i++)
  //     speed[i].classList.remove('active')
  //   e.target.classList.add('active')
  // })
  /*----------------------------控制区 end---------------------------*/


})

/*--------------------------获取时间----------------------------*/
let getCurrentTime = () => {
  const currentTime = new Date()
  const year = currentTime.getFullYear()
  const month = (currentTime.getMonth() + 1).toString().padStart(2, '0')
  const day = currentTime.getDate().toString().padStart(2, '0')
  const hour = currentTime.getHours().toString().padStart(2, '0')
  const minute = currentTime.getMinutes().toString().padStart(2, '0')
  const second = currentTime.getSeconds().toString().padStart(2, '0')

  const timeStr = `${year}年${month}月${day}日 ${hour}:${minute}:${second}`
  document.querySelector('.time b').innerHTML = timeStr;
}

/*--------------------------获取天气----------------------------*/
const apiKey = '8b557d6b65c8f5ede22411f8717e54c3';
const apiUrl = 'https://api.openweathermap.org/data/2.5/weather?q=jinan';

async function getWeather() {
  const response = await fetch(`${apiUrl}&appid=${apiKey}&units=metric&lang=zh`);
  const data = await response.json();
  displayWeather(data);
}

function displayWeather(data) {
  const bs = document.querySelectorAll('.weather b')
  bs[0].innerHTML = `${data.weather[0].description}`
  bs[1].innerHTML = `${data.main.temp}℃`
  bs[2].innerHTML = `${data.main.humidity}%`
  // document.getElementById('wind-speed').innerText = `风速: ${data.wind.speed} m/s`;
}

var xhr = new XMLHttpRequest();
var url = "";
/*------------------------------数据显示区-------------------------------- */
let get_info = () => {
  // 给服务器发送消息
  xhr.open("POST", url, true);

  xhr.onreadystatechange = function ()////当状态发生变化
  {
    if (xhr.readyState === 4 && xhr.status === 200)
    // 响应正文:xhr.responseText
    {
      var z = (xhr.responseText).split('\n')
      // console.log(z);
      /************************************
       *  处理数据
      ************************************/
      const datab = document.querySelectorAll('.show b')
      for (let i = 0; i < z.length; i++) {
        const map = z[i].split(' ')
        // console.log(map);
        if (map[0] == 301) {  // 体温
          datab[2].innerHTML = `${map[1]}℃`
        } else if (map[0] == 303) {  // 心率
          datab[3].innerHTML = `${map[1]}`
        }
        else if (map[0] == 312) { // 步数
          datab[4].innerHTML = `${map[1]}步`
        }
        else if (map[0] == 101) { // 室内温度
          datab[0].innerHTML = `${map[1]}℃`
        }
        else if (map[0] == 102) { // 室内湿度
          datab[1].innerHTML = `${map[1]}℃`
        }
      }
    }
  }
  xhr.send("get");  // 发送消息
}

/*------------------------------控制区-------------------------------- */

// 改变设备状态
let change_statu = (addr, flag) => {
  xhr.open("post", url, true);

  flag == 1 ? xhr.send(`"set ${addr}1"`) : xhr.send(`"set ${addr}0"`)
}